from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Date, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from datetime import datetime, date
from typing import Optional, List

Base = declarative_base()

class User(Base):
    """
    用户模型
    存储用户基本信息和认证信息
    """
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(100), unique=True, index=True, nullable=False)
    hashed_password = Column(String(255), nullable=False)
    nickname = Column(String(100), nullable=True)
    avatar = Column(String(255), nullable=True, default="/img/thumb.jpg")
    is_active = Column(Boolean, default=True)
    is_verified = Column(Boolean, default=False)
    
    # 认证相关字段
    email_verified = Column(Boolean, default=False)  # 邮箱认证状态
    phone = Column(String(20), nullable=True)  # 手机号
    phone_verified = Column(Boolean, default=False)  # 手机认证状态
    real_name = Column(String(50), nullable=True)  # 真实姓名
    id_card = Column(String(18), nullable=True)  # 身份证号
    real_name_verified = Column(Boolean, default=False)  # 实名认证状态
    
    # 微信登录相关
    wechat_openid = Column(String(100), unique=True, nullable=True)
    wechat_unionid = Column(String(100), unique=True, nullable=True)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    works = relationship("Work", back_populates="user", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<User(id={self.id}, username='{self.username}')>"

class Work(Base):
    """
    作品模型
    存储用户上传的AI生成作品信息
    """
    __tablename__ = "works"
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(200), nullable=False)
    description = Column(Text, nullable=True)
    category = Column(String(50), nullable=False)  # image/video/music/text
    tags = Column(JSON, nullable=True, default=[])
    
    # 文件相关
    file_url = Column(String(500), nullable=False)
    thumbnail = Column(String(500), nullable=True)
    file_size = Column(Integer, nullable=True)
    mime_type = Column(String(100), nullable=True)
    
    # 统计数据
    views = Column(Integer, default=0)
    likes = Column(Integer, default=0)
    comments = Column(Integer, default=0)
    
    # 外键
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    contest_id = Column(Integer, ForeignKey("contests.id"), nullable=True)  # 竞赛作品关联
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    user = relationship("User", back_populates="works")
    contest = relationship("Contest", back_populates="works")
    likes_rel = relationship("WorkLike", back_populates="work", cascade="all, delete-orphan")
    favorites_rel = relationship("WorkFavorite", back_populates="work", cascade="all, delete-orphan")
    comments_rel = relationship("WorkComment", back_populates="work", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Work(id={self.id}, title='{self.title}', category='{self.category}')>"

class Contest(Base):
    """
    竞赛模型
    存储AI创作竞赛信息
    """
    __tablename__ = "contests"
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(300), nullable=False)
    description = Column(Text, nullable=True)
    rules = Column(Text, nullable=True)
    
    # 竞赛时间
    start_date = Column(Date, nullable=False)
    end_date = Column(Date, nullable=False)
    
    # 竞赛状态: upcoming/ongoing/ended
    status = Column(String(20), nullable=False, default="upcoming")
    
    # 竞赛信息
    prize = Column(Text, nullable=True)
    organizer = Column(String(200), nullable=True)
    category = Column(String(50), nullable=True)  # video/image/music/text
    
    # 统计数据
    participant_count = Column(Integer, default=0)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    works = relationship("Work", back_populates="contest")
    
    def __repr__(self):
        return f"<Contest(id={self.id}, title='{self.title}', status='{self.status}')>"

class AITool(Base):
    """
    AI工具模型
    存储可搜索的AI工具信息
    """
    __tablename__ = "ai_tools"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    description = Column(Text, nullable=True)
    icon = Column(String(500), nullable=True)
    url = Column(String(500), nullable=False)
    category = Column(String(50), nullable=False)
    tags = Column(JSON, nullable=True, default=[])
    
    # 评分和热度
    rating = Column(Integer, default=0)  # 0-50 (实际显示时除以10)
    popularity = Column(Integer, default=0)
    
    # 状态
    is_active = Column(Boolean, default=True)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    def __repr__(self):
        return f"<AITool(id={self.id}, name='{self.name}', category='{self.category}')>"

class WeChatQR(Base):
    """
    微信二维码模型
    存储微信登录二维码信息
    """
    __tablename__ = "wechat_qr"
    
    id = Column(Integer, primary_key=True, index=True)
    qr_id = Column(String(100), unique=True, nullable=False)
    qr_code = Column(Text, nullable=False)  # base64编码的二维码图片
    status = Column(String(20), default="waiting")  # waiting/scanned/success/expired
    
    # 关联的用户ID（扫码成功后设置）
    user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    
    # 过期时间
    expire_time = Column(Integer, default=120)  # 秒
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    def __repr__(self):
        return f"<WeChatQR(qr_id='{self.qr_id}', status='{self.status}')>"

class WorkLike(Base):
    """
    作品点赞模型
    存储用户对作品的点赞记录
    """
    __tablename__ = "work_likes"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    work_id = Column(Integer, ForeignKey("works.id"), nullable=False)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关联关系
    user = relationship("User")
    work = relationship("Work", back_populates="likes_rel")
    
    def __repr__(self):
        return f"<WorkLike(user_id={self.user_id}, work_id={self.work_id})>"

class WorkFavorite(Base):
    """
    作品收藏模型
    存储用户对作品的收藏记录
    """
    __tablename__ = "work_favorites"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    work_id = Column(Integer, ForeignKey("works.id"), nullable=False)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关联关系
    user = relationship("User")
    work = relationship("Work", back_populates="favorites_rel")
    
    def __repr__(self):
        return f"<WorkFavorite(user_id={self.user_id}, work_id={self.work_id})>"

class WorkComment(Base):
    """
    作品评论模型
    存储用户对作品的评论
    """
    __tablename__ = "work_comments"
    
    id = Column(Integer, primary_key=True, index=True)
    content = Column(Text, nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    work_id = Column(Integer, ForeignKey("works.id"), nullable=False)
    parent_id = Column(Integer, ForeignKey("work_comments.id"), nullable=True)  # 回复评论
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    user = relationship("User")
    work = relationship("Work", back_populates="comments_rel")
    parent = relationship("WorkComment", remote_side=[id])
    
    def __repr__(self):
        return f"<WorkComment(id={self.id}, user_id={self.user_id}, work_id={self.work_id})>"

class ContestParticipant(Base):
    """
    竞赛参与者模型
    存储用户参与竞赛的记录
    """
    __tablename__ = "contest_participants"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    contest_id = Column(Integer, ForeignKey("contests.id"), nullable=False)
    
    # 参与状态: joined/submitted/withdrawn
    status = Column(String(20), default="joined")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    user = relationship("User")
    contest = relationship("Contest")
    
    def __repr__(self):
        return f"<ContestParticipant(user_id={self.user_id}, contest_id={self.contest_id}, status='{self.status}')>"

class WorkShare(Base):
    """
    作品转发模型
    存储用户转发作品的记录
    """
    __tablename__ = "work_shares"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    work_id = Column(Integer, ForeignKey("works.id"), nullable=False)
    
    # 转发平台: wechat/weibo/qq/link
    platform = Column(String(20), nullable=False)
    
    # 转发备注
    comment = Column(Text, nullable=True)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关联关系
    user = relationship("User")
    work = relationship("Work")
    
    def __repr__(self):
        return f"<WorkShare(user_id={self.user_id}, work_id={self.work_id}, platform='{self.platform}')>"